package com.uam.core.tool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * RestTemplateUtils 请求的帮助类型
 *
 * @author heguanglong
 * @Data 2021-04-14
 */
@Component
@Slf4j
public class RestTemplateUtils {
    @Resource
    private RestTemplate restTemplate;

    public String postFormData(String url, MultiValueMap<String, Object> map) {
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, getFormDataHttpHeaders());
        return sendPostHttp(url, param);
    }

    private HttpHeaders getFormDataHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return headers;
    }


    private String sendPostHttp(String url, HttpEntity<MultiValueMap<String, Object>> param) {
        ResponseEntity<String> response = restTemplate.postForEntity(url, param, String.class);
        return response.getBody();
    }

    public String httpGet(String url, Map<String, Object> param) {
        StringBuilder stringBuilder = new StringBuilder(url + "?");
        if (param != null) {
            param.entrySet().forEach(e -> {
                stringBuilder.append(e.getKey()).append("=").append(e.getValue()).append("&");
            });
        }
        String urlAndParam = stringBuilder.toString();
        log.info("url={}",urlAndParam);
        ResponseEntity<String> responseEntity = httpGet(urlAndParam);
        return responseEntity.getBody();
    }

    public ResponseEntity<String> httpGet(String urlAndParam) {
        return restTemplate.exchange(urlAndParam, HttpMethod.GET, null, String.class);
    }
}
